package com.x.ant.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {
//	public static void  main(String[] args){
//		Map<String, String> map = new HashMap<>();
//		map.put("comid","1489");
//		map.put("username","hxgd");
//		map.put("userpwd","761991");
//		map.put("smsnumber","10690");
//		map.put("handtel","13439476895");
//		map.put("sendcontent","aaaa");
//		map.put("sendtime","");
//		try {
//			System.out.println(doGet("http://jiekou.56dxw.com/sms/HttpInterface.aspx",map));
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	public static String doGet(String url, Map<String, String> param) throws Exception {

		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);

			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
			return resultString;
		} finally {
			if (response != null) {
				response.close();
			}
			httpclient.close();
		}
	}

	public static String doGet(String url) throws Exception {
		return doGet(url, null);
	}

	public static String doPost(String url, Map<String, String> param) throws Exception {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建参数列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
			return resultString;
		} finally {
			response.close();
			httpClient.close();
		}
	}

	public static String doPost(String url) throws Exception {
		return doPost(url, null);
	}

	public static String doPostJson(String url, String json) throws Exception {
		CloseableHttpResponse closeableHttpResponse = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		try {
			// 创建Httpclient对象
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			closeableHttpResponse = httpClient.execute(httpPost);
			return EntityUtils.toString(closeableHttpResponse.getEntity(), "utf-8");
		} finally {
			if (closeableHttpResponse != null) {
				closeableHttpResponse.close();
			}
			httpClient.close();
		}
	}

	public static String uploadFile(File file, String url, Map<String, String> params) {
		CloseableHttpClient httpClient = HttpClients.createDefault();

		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			HttpPost httpPost = new HttpPost(url);
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();

			builder.addPart("file", new FileBody(file));
			// StringBody
			for (Entry<String, String> en : params.entrySet()) {
				builder.addPart(en.getKey(), new StringBody(en.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
			}

			HttpEntity reqEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build();

			httpPost.setEntity(reqEntity);

			// 发起请求 并返回请求的响应
			response = httpClient.execute(httpPost);

			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String sendMessage(String mibile, String verifyCode) throws Exception {
		//?comid=企业ID&username=用户名&userpwd=密码&handtel=手机号&sendcontent=内容限制为70个字，小灵通60个字&sendtime=定时时间&smsnumber=所用平台
		HttpURLConnection httpurlconnection = null;
		try {
			String sendMessage = java.net.URLEncoder.encode(verifyCode + "（验证码，请勿泄露）,感谢您的支持！", "gbk");
			String url_sendMessage = "http://jiekou.56dxw.com/sms/HttpInterface.aspx?comid=1489&username=hxgd&userpwd=761991&smsnumber=10690&sendtime=&sendcontent="+sendMessage+"&handtel=" + mibile;
			System.out.println(url_sendMessage);
			URL url = new URL(url_sendMessage);
			// 以post方式请求
			httpurlconnection = (HttpURLConnection) url.openConnection();
			httpurlconnection.setDoOutput(true);
			httpurlconnection.setRequestMethod("GET");
			// 获取响应代码
			int code = httpurlconnection.getResponseCode();
			// 获取页面内容
			StringBuffer sb = new StringBuffer();
			BufferedReader in = new BufferedReader(new InputStreamReader(httpurlconnection
					.getInputStream(), "gbk"));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				sb.append(inputLine);
			}
			int i = Integer.parseInt(sb.toString());
			System.out.println(i);
			String result = "";
			switch (i) {
				case -1:
					result = "手机号码不正确";
				case -2:
					result = "除时间外，所有参数不能为空";
				case -3:
					result = "用户名密码不正确";
				case -4:
					result = "平台不存在";
				case -5:
					result = "客户短信数量为0";
				case -6:
					result = "客户账户余额小于要发送的条数";
				case -7:
					result = "不能超过70个字";
				case -8:
					result = "非法短信内容";
				case -9:
					result = "未知系统故障";
				case -10:
					result = "网络性错误";
				case -21:
					result = "要加签名";
				case 1:
					result = "发送成功";
			}
			return result;
		} finally {
			if (httpurlconnection != null)
				httpurlconnection.disconnect();
		}
	}

	public static void main(String[] arg){
		try {
			sendMessage("13439476895", "3333");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
